package com.note.notes.dao.impl;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.date.DateUtil;
import com.note.common.constants.TCNameConstants;
import com.note.common.domain.Note;
import com.note.common.domain.Share;
import com.note.notes.dao.NoteRepository;
import com.note.notes.pojo.NoteUpdatePojo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @Package：com.note.notes.dao.impl
 * @Name：NoreRepositoryImpl
 * @Author：热伊木
 * @Email：uyevan@163.com
 * @Date：2023-12-21-12:07
 * @Description：笔记业务数据库操作实现
 */
@Slf4j
@Repository
public class NoteRepositoryImpl implements NoteRepository {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void insertNote(Note note) {
        /*存入文档*/
        mongoTemplate.insert(note, TCNameConstants.NOTE);
    }

    @Override
    public void deleteNote(String noteId, String username) {
        /*条件*/
        Query query = new Query(
                Criteria.where("id").is(noteId)
                        .and("user_id").is(username)
                        .and("deleted").is(0)
        );
        Update update = new Update();
        update.set("deleted", 1);
        mongoTemplate.updateFirst(query, update, Note.class);
    }

    @Override
    public List<Note> deleteAllNoteByFolderId(String folderId, String username) {
        Query query = new Query(
                Criteria.where("folder_id").is(folderId)
                        .and("user_id").is(username)
                        .and("deleted").is(0)
        );

        // return mongoTemplate.findAllAndRemove(query, Note.class); //直接物理删除

        /**
         * 逻辑删除
         */
        List<Note> noteToDeleted = mongoTemplate.find(query, Note.class);//待删除的笔记
        Update update = new Update();
        update.set("deleted", 1);
        mongoTemplate.updateMulti(query, update, Note.class);//更新多个
        return noteToDeleted;
    }

    @Override
    public void updateNote(NoteUpdatePojo noteUpdatePojo) {
        /*更新条件*/
        Query query = new Query(
                Criteria.where("id").is(noteUpdatePojo.getNoteId())
                        .and("user_id").is(noteUpdatePojo.getUsername())
                        .and("folder_id").is(noteUpdatePojo.getFolderId())
                        .and("deleted").is(0)
        );
        /*更新数据*/
        Update update = new Update();
        update.set("title", noteUpdatePojo.getTitle());
        update.set("icon", noteUpdatePojo.getIcon());
        update.set("content", noteUpdatePojo.getContent());
        update.set("folder_id", noteUpdatePojo.getFolderId());
        update.set("tag_id", noteUpdatePojo.getTagId());
        update.set("update_time", DateUtil.date());
        /*执行更新（第一个）*/
        mongoTemplate.updateFirst(query, update, Note.class);
    }

    @Override
    public List<Note> selectNotes(String folderId, String username) {
        Query query = new Query(
                Criteria.where("folder_id").is(folderId)
                        .and("user_id").is(username)
                        .and("deleted").is(0)
        );
        //不返回content笔记内容
        query.fields().exclude("content");
        return mongoTemplate.find(query, Note.class);
    }

    @Override
    public Note selectNote(String noteId, String username) {
        Query query = new Query(
                Criteria.where("id").is(noteId)
                        .and("user_id").is(username)
                        .and("deleted").is(0)
        );
        return mongoTemplate.findOne(query, Note.class);
    }

    @Override
    public Note selectNote(String noteId) {
        Query query = new Query(
                Criteria.where("id").is(noteId)
                        .and("deleted").is(0)
        );
        return mongoTemplate.findOne(query, Note.class);
    }

    @Override
    public boolean isSharedNote(String noteId) {
        Query query = new Query(
                Criteria.where("note_id").is(noteId)
                        .and("type").is(1)
                        .and("deleted").is(0)
        );
        return mongoTemplate.exists(query, TCNameConstants.SHARE);
    }

    @Override
    public String getSharedId(String noteId) {
        Query query = new Query(
                Criteria.where("note_id").is(noteId)
                        .and("deleted").is(0)
        );
        Share share = mongoTemplate.findOne(query, Share.class, TCNameConstants.SHARE);
        if (share != null) {
            return share.getId();
        } else {
            /*throw new RuntimeException("该分享不存在,请重试");*/
            return "0";
        }
    }

    @Override
    public List<Note> searchNoteByLike(String username, String keyword) {
        String decodeKeyword = Base64Decoder.decodeStr(keyword).replace("\"", "");
        //模糊条件
        Pattern patternDecodeKeyword = Pattern.compile("^.*" + decodeKeyword + ".*$");
        Pattern patternContent = Pattern.compile("^.*" + keyword + ".*$");
        Query query = new Query(Criteria
                .where("user_id").is(username)
                .andOperator(
                        new Criteria().orOperator(
                                Criteria.where("title").regex(patternDecodeKeyword),
                                Criteria.where("content").regex(patternContent)
                        )
                ) //标题+内容模糊查询
                /*.and("title").regex(patternDecodeKeyword) 标题模糊查询*/
                .and("deleted").is(0)
        );
        query.fields().exclude("content");
        log.info("query:{}", query.getQueryObject());
        log.info("query:{}", query.getFieldsObject());
        return mongoTemplate.find(query, Note.class);
    }
}
